使用Ruby on rails 發開網站時常常會用到第三方登入,今天就來實際操作使用 Devise 套件 + Google 的三方登入吧
Step 1
請先至 Google 申請 API 金鑰
Step 2
到專案裡的 Gemfile 新增以下程式碼
gem "omniauth", "~> 2.1"
gem 'omniauth-google-oauth2'
gem 'omniauth-rails_csrf_protection'
輸入安裝指令
$ bundle install
step 3
建立第三方資料的 Model
$ rails g migration add_omniauth_to_users
class AddOmniauthToUsers < ActiveRecord::Migration[7.0]
def change
add_column :users, :provider, :string
add_column :users, :uid, :string
end
end
跑一下db:migrate
$ rails db:migrate
step 4
加入 API 帳號密碼
在 config/initializers/devise.rb 裡面的
Devise.setup do |config|
新增以下
config.omniauth :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"],{}
註: 這邊使用dotenv 套件 ENV 環境變數來儲存 API 金鑰
step 5
在 User Model 裡更新 devise 允許使用 OmniAuth
devise :omniauthable, omniauth_providers: %i[google_oauth2]
step 6
設定 Routes
devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }
step 7
在 user 資料夾底下建立 controller:omniauth_callbacks_controller.rb
module Users
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
# callback for google
def google_oauth2
callback_for(:google)
end
# common callback method
def callback_for(provider)
@user = User.from_omniauth(request.env['omniauth.auth'])
if @user.persisted?
flash[:notice] = I18n.t 'devise.omniauth_callbacks.success', kind: provider
redirect_to welcome_profiles_path
else
session['devise.auth_data'] = request.env['omniauth.auth'].except('extra')
redirect_to welcome_profiles_path, alert: @user.errors.full_messages.join("\n")
end
end
def failure
redirect_to root_path, notice: '驗證失敗'
end
end
end
step 8
回到 User Model 寫身分驗證的方法
def self.from_omniauth(access_token)
data = access_token.info
user = User.where(email: data['email']).first
# Uncomment the section below if you want users to be created if they don't exist
user ||= User.create(
email: data['email'],
name: data['name'] || data['email'].split('@').first,
password: Devise.friendly_token[0, 16]
)
user
end
這麼一來應該就可以成功串接到 Google 登入囉
明天預計來介紹 DNS 跟 IP ,我們明天見!